package com.alex.alexelasticsearch.controller;

import com.alex.alexelasticsearch.model.Alex008Product;
import com.alex.alexelasticsearch.service.Alex008ProductSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 商品搜索控制器
 * 提供 RESTful API 接口供前端调用
 */
@RestController
@RequestMapping("/api/products")
@CrossOrigin(origins = "*")  // 允许跨域，方便前端调用
public class Alex008ProductController {

    @Autowired
    private Alex008ProductSearchService searchService;

    /**
     * 返回搜索页面
     * GET /
     */
    @GetMapping("/")
    public String index() {
        return "forward:/index.html";
    }

    /**
     * 初始化测试数据
     * GET /api/products/init-data
     */
    @GetMapping("/init-data")
    public ResponseEntity<Map<String, String>> initData() {
        try {
            searchService.initTestData();
            return ResponseEntity.ok(Map.of(
                "status", "success",
                "message", "测试数据初始化成功"
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", "初始化失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 简单搜索
     * GET /api/products/search?keyword=iPhone
     */
    @GetMapping("/search")
    public ResponseEntity<List<Alex008Product>> simpleSearch(
            @RequestParam String keyword) {
        List<Alex008Product> results = searchService.simpleSearch(keyword);
        return ResponseEntity.ok(results);
    }

    /**
     * 高级搜索 - 支持多条件筛选和排序
     * GET /api/products/advanced-search?keyword=手机&category=手机&brand=Apple&minPrice=1000&maxPrice=10000&sortBy=price&sortOrder=desc&page=0&size=10
     */
    @GetMapping("/advanced-search")
    public ResponseEntity<Map<String, Object>> advancedSearch(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String brand,
            @RequestParam(required = false) BigDecimal minPrice,
            @RequestParam(required = false) BigDecimal maxPrice,
            @RequestParam(defaultValue = "salesCount") String sortBy,
            @RequestParam(defaultValue = "desc") String sortOrder,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            Page<Alex008Product> results = searchService.advancedSearch(
                keyword, category, brand, minPrice, maxPrice, 
                sortBy, sortOrder, page, size
            );
            
            return ResponseEntity.ok(Map.of(
                "products", results.getContent(),
                "totalElements", results.getTotalElements(),
                "totalPages", results.getTotalPages(),
                "currentPage", results.getNumber(),
                "size", results.getSize(),
                "hasNext", results.hasNext(),
                "hasPrevious", results.hasPrevious()
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "error", "搜索失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 搜索并高亮显示
     * GET /api/products/search-highlight?keyword=iPhone
     */
    @GetMapping("/search-highlight")
    public ResponseEntity<List<Map<String, Object>>> searchWithHighlight(
            @RequestParam String keyword) {
        List<Map<String, Object>> results = searchService.searchWithHighlight(keyword);
        return ResponseEntity.ok(results);
    }

    /**
     * 搜索建议/自动补全
     * GET /api/products/suggestions?prefix=iP
     */
    @GetMapping("/suggestions")
    public ResponseEntity<List<String>> getSearchSuggestions(
            @RequestParam String prefix) {
        List<String> suggestions = searchService.getSearchSuggestions(prefix);
        return ResponseEntity.ok(suggestions);
    }

    /**
     * 获取聚合统计信息
     * GET /api/products/stats
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getStats() {
        Map<String, Object> stats = searchService.getAggregationStats();
        return ResponseEntity.ok(stats);
    }

    /**
     * 根据分类获取商品 - 演示精确匹配
     * GET /api/products/by-category/手机
     */
    @GetMapping("/by-category/{category}")
    public ResponseEntity<List<Alex008Product>> getByCategory(
            @PathVariable String category) {
        // 这里直接调用 repository，演示不同的查询方式
        List<Alex008Product> products = searchService.simpleSearch(category);
        return ResponseEntity.ok(products);
    }
}